package ltd.followkba.page;

import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;
import com.kcbsdk.EventHandler;

import java.util.ArrayList;
import java.util.List;

import ltd.advskin.MSKIN;
import ltd.advskin.base.BaseList;
import ltd.advskin.base.BasePage;

import ltd.advskin.base.KcListHolder;
import ltd.advskin.base.KcListListener;
import ltd.advskin.base.KcTypeListener;
import ltd.advskin.task.TaskFree;
import ltd.advskin.view.KcHeaderView;
import ltd.advskin.view.KcListView;
import ltd.followkba.MAPP;
import ltd.followkba.MDBS;
import ltd.followkba.R;
import ltd.followkba.task.BAppUser;
import ltd.followkba.task.EditUtils;
import ltd.followkba.task.RunUtils;
import main.MAPI;

import static ltd.advskin.MSKIN.MSTRING;
import static ltd.advskin.MSKIN.MTOAST;
import static main.MAPI.mMyUtils;
import static main.MAPI.mMyWorks;

public class SelectUserPage extends BaseList {
    private byte gWorksType;
    private List<BAppUser>[] mBAppUser;


    // 所有的页面都接受同样的方式打开LOG
    public static boolean logEnable;

    public void MLOG(String text) {
        if (logEnable) {
            MSTRING(MAPI.GET_LOG_NAME(this) + text);
        }
    }

    @Override
    public void onInitView() {                       // 使用者需要继承，初始化页面控件等显示
        setLayout(R.layout.page_select_user);
        boolean noTab = false;
        if (mBaseInput != null) {                   // 可能仅仅需要刷新，未必是重新开始的
            noTab = mBaseInput.getInput(0);
            mBaseInput = null;                  // 输入参数的使命已经完成，记得及时销毁之
        }
        mKcHeaderView = (KcHeaderView) findViewById(R.id.khvSelect);
        if (!noTab) {
            gWorksType = MAPP.mBDbsAccount.SelectWorksType;
        }else {
            gWorksType = MAPP.mBDbsAccount.WorksType;
        }
        String text = String.format("选择%s用户",  MAPP.mWorksName[gWorksType]);
        mKcHeaderView.setTitle(text, new KcTypeListener() {
            @Override
            public void onMessage(int type) {
                switch (type) {
                    case KcHeaderView.TYPE_CLICK_LEFT:
                        onFinish();
                        break;

                }
            }
        });

        findViewById(R.id.vSelect).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {                                      // 查找
                byte worksType = (gTabQty < 2) ? gWorksType :MAPP.mWorksType[gTabSelect];           // 作品类型
                MAPP.startSearchUserPage(worksType);
            }
        });
        findViewById(R.id.kbtSearchSelect).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {                              // 查找
                byte worksType = (gTabQty < 2) ? gWorksType : MAPP.mWorksType[gTabSelect];          // 作品类型
                MAPP.startSearchUserPage(worksType);
            }
        });
        mBAppUser = new List[MAPP.mWorksType.length];
        if (!noTab) {
            for (int index = 0; index < MAPP.mWorksType.length; index++) {
                if (gWorksType == MAPP.mWorksType[index]) {
                    gTabSelect = (byte) index;
                }
            }
            initPageListView(noTab ? 1 : MAPP.mWorksName.length);
        }else {
            initPageListView(1);
        }
    }


    @Override
    public void onInitData(){                                                                       // onInitView结束，开始加载数据
        mMyWorks.setUiEventCallBack(new EventHandler() {
            @Override
            public void onComplete(int methodType, boolean isFail, String message) {
                if (mMyWorks.isEventDataRefresh()){
                    MLOG(String.format("showInfoA isEventDataRefresh"));
                    showInfo();
                }
            }
        });
        showInfo();
    }
    @Override
    public void onPageUpdate(BasePage basePage){
        Object object = getPageResult(basePage);
//        MLOG(String.format("showInfoA1 %s(%s)",  gTabSelect, mBAppUser[gTabSelect]));
        if (object != null) {
            MLOG(String.format("showInfoA11 %s(%s)",  gTabSelect, mBAppUser[gTabSelect]));
            mBAppUser[gTabSelect] = null;
            if (basePage instanceof SearchUserPage){
                MTOAST("温馨提示，点击整行选择。\n一般不需要点击头像", 3000);
            }
        }
        onInitData();
    }

    private void showInfo(){
        int tabSel = getTabList();
//        MLOG(String.format("showInfoA2a %s",  tabSel));
        if (tabSel > 0) {
            tabSel -= 1;
            MLOG(String.format("showInfoA2 %s(%s)",  tabSel, mBAppUser[tabSel]));
            if (mBAppUser[tabSel] == null) {
                makeLists(tabSel);
            }
            setListView(tabSel, (List) mBAppUser[tabSel]);
        }
    }
    private void makeLists(int tabSel){
        mBAppUser[tabSel] = new ArrayList<>();
        new TaskFree(tabSel, new TaskFree.Listener() {
            @Override
            public void onMessage(boolean isThread, Object object) {
                int tabSel = (int) object;
                if (isThread) {
                    byte worksType = (gTabQty < 2) ? gWorksType :MAPP.mWorksType[gTabSelect];
                    mBAppUser[tabSel] = MDBS.getSearchUser(MAPP.mBDbsAccount, worksType);
                    int length = (mBAppUser[tabSel] != null) ? mBAppUser[tabSel].size() : 0;
                    MLOG(String.format("HomeA showInfoA3 %s(%s)",  tabSel, length));
                    return;
                }
                if (mBAppUser[tabSel] != null) {
                    showInfo();
                }
            }
        });
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // KcListView的全部处理，放在页面的最后位置统一处理 ///////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    public void initListView(int tab, KcListView kcListView) {
        mKcListView[tab] = kcListView;
        mKcListView[tab].initView(null, MAPP.item_user_select, null, new KcListListener() {
            @Override
            public int onMessage(int type, int tab, Object object) {
                return 0;
            }
            @Override
            public int onBindItemHolder(boolean skipImage, int tab, int position, final KcListHolder holder) {
                BAppUser bAppUser = (BAppUser)getListView(tab, position);
                if (bAppUser != null) {
                    holder.mView[0].setVisibility(View.GONE);
                    MAPP.showUserHead(bAppUser.HeadFile, bAppUser, holder.mView[1]);
                    MSKIN.setText(bAppUser.UserName, holder.mView[2]);
                    String text = MAPP.getUser(bAppUser);// String.format("粉%s关%s歌%s %s", bAppUser.FansQty, bAppUser.CareQty, bAppUser.WorksQty, bAppUser.City);
                    MSKIN.setText(text, holder.mView[3]);

                    holder.mView[1].setTag(bAppUser);
                    holder.mView[1].setTag(R.id.tag_0, tab);
                    holder.mView[1].setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            BAppUser bAppUser = (BAppUser) v.getTag();
                            int tab = (int) v.getTag(R.id.tag_0);
                            bAppUser.WorksType = (gTabQty < 2) ? gWorksType :MAPP.mWorksType[gTabSelect];
//                            bAppUser.WorksType = MAPP.mWorksType[tab];              // 作品类型
                            MAPP.startUserHomePage(bAppUser, false);
                        }
                    });
                    holder.mItemView.setTag(bAppUser);
                    holder.mItemView.setTag(R.id.tag_0, tab);
                    holder.mItemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            BAppUser bAppUser = (BAppUser) v.getTag();
                            MTOAST(String.format("已选择%s用户%s",  MAPP.mWorksName[bAppUser.WorksType], bAppUser.UserName));
                            setPageResult(bAppUser);
                            setClose();
                        }
                    });
                    if (bAppUser.WorksType == MAPP.mBDbsAccount.WorksType && bAppUser.UserIdS.equals(MAPP.mBDbsAccount.UserIdS)){
                        MSKIN.setText("自己", holder.mView[4]);
                    }else if (bAppUser.WorksType == MAPP.mBDbsAccount.CloneAppType && bAppUser.UserIdS.equals(MAPP.mBDbsAccount.CloneUserIdS)){
                        MSKIN.setText("克隆", holder.mView[4]);
                    }else {
                        MSKIN.setText("删除", holder.mView[4]);
                        holder.mView[4].setTag(bAppUser);
                        holder.mView[4].setTag(R.id.tag_0, tab);
                        holder.mView[4].setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                BAppUser bAppUser = (BAppUser) v.getTag();
                                int tab = (int) v.getTag(R.id.tag_0);
                                byte worksType = (gTabQty < 2) ? gWorksType :MAPP.mWorksType[gTabSelect];
                                MDBS.delSearchUser(MAPP.mBDbsAccount, worksType, bAppUser);
                                makeLists(tab);
//                            showInfo();
                                MTOAST(String.format("已删除%s", bAppUser.UserName));
                            }
                        });
                    }
                }
                return 0;
            }
        });
        // (d)列表最后更新日期时间 (n)下次更新日期时间 (c)当前数量 (q)列表最大的数量
        mKcListView[tab].setStatus(false, false, "", "点击“查找”添加新用户", null);
        mKcListView[tab].setTabNumber(tab);
    }

    private void initPageListView(int tabQty) {
        mKcListView = new KcListView[tabQty];
        if (tabQty == 1) {
            mKcListView[0] = findViewById(R.id.klvSelect);
            mKcListView[0].setVisibility(View.VISIBLE);
            initListView(0, mKcListView[0]);
            return;
        }
        gTabQty = (byte) tabQty;
        ViewPager viewPager = findViewById(R.id.vpSelect);
        TabLayout tabLayout = findViewById(R.id.tlSelect);;
        mKcListView = new KcListView[tabQty];
        mPagerAdapter = new PagerAdapter() {
            @Override
            public int getCount() {
                return MAPP.mWorksType.length;
            }
            @Override
            public CharSequence getPageTitle(int position) {
                int worksType = MAPP.mWorksType[position];
                return MAPP.mWorksName[worksType];
            }
            @Override
            public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
                return view == object;
            }
            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                KcListView kcListView = new KcListView(getActivity(), null);
                initListView(position, kcListView);
                container.addView(kcListView);
                setTabList(position);                               // 设置Tab的位置
                return kcListView;
            }
            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView(mKcListView[position]);
                mKcListView[position] = null;
            }
        };
        viewPager.setAdapter(mPagerAdapter);
        viewPager.setCurrentItem(gTabSelect);
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);       // 设置TabLayout的模式   MODE_SCROLLABLE为滑动模式  MODE_FIXED为不滑动模式
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }
            @Override
            public void onTabSelected(TabLayout.Tab tab) {   // 顶部Tab选择
                byte tabSel = (byte) tab.getPosition();
                if (gTabSelect != tabSel) {                 // Tab的选择
                    gTabSelect = tabSel;
                    setTabList(tabSel);                     // 设置Tab的位置
                    if (gTabQty > 1) {
                        MAPP.mBDbsAccount.SelectWorksType = MAPP.mWorksType[gTabSelect];
                        MDBS.setBDbsAccount(MAPP.mBDbsAccount);
                    }
                }
            }
            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }

}


